const PARKING_TOKEN_KEY = "PARKING_TOKEN_KEY";
const PARKING_TOKEN_STORAGE_LONG_KEY = "Lisence-Plate-Warning-Storage";
const Lisence_Plate_Warning_token = "Lisence-Plate-Warning-Token"

interface TokenData {
  access_token: string;
  expires_in: number;
  refresh_token: string;
}

interface UserInfo {
  avatarPath: string;
  nickName: string;
  username: string;
  userType: number | string;
  code: string;
  id: number | string;
  [props: string]: any;
}

interface UserObj {
  domain: string;
  passId: string;
  user: UserInfo;
}
interface loginInfo {
  tokenData: TokenData;
  user: UserObj;
}

function getStorageInstance() {
  return getStorageLong() ? window.localStorage : window.sessionStorage;
}

// Token
export function getUserLoginInfo() {
  const storage = getStorageInstance();
  const data = storage.getItem(PARKING_TOKEN_KEY);
  return data === null ? null : JSON.parse(data);
}

export function setUserLoginInfo(data: loginInfo) {
  // 过期时间减去10秒，保证安全
  const { tokenData } = data;
  tokenData.expires_in = Date.now() + (tokenData.expires_in - 10) * 1000;
  const storage = getStorageInstance();
  return storage.setItem(PARKING_TOKEN_KEY, JSON.stringify(data));
}

export function removeUserLoginInfo() {
  const storage = getStorageInstance();
  return storage.removeItem(PARKING_TOKEN_KEY);
}

// 设置长期存储标记
export function setStorageLong(val: boolean) {
  return localStorage.setItem(PARKING_TOKEN_STORAGE_LONG_KEY, val ? "1" : "0");
}

// 获取长期存储标记
export function getStorageLong() {
  return localStorage.getItem(PARKING_TOKEN_STORAGE_LONG_KEY) === "1";
}

// 长期存储标记清除
export function removeStorageLong() {
  return localStorage.removeItem(PARKING_TOKEN_STORAGE_LONG_KEY);
}


// 设置token
export function setUserToken(data: loginInfo) {
  return localStorage.setItem(Lisence_Plate_Warning_token, data);
}

// 获取token
export function getUserToken() {
  return localStorage.getItem(Lisence_Plate_Warning_token);
}